package com.javasm.mingming.login.phone;

import com.javasm.mingming.common.utils.RequestBodyUtil;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author javasm
 * @version 0.1
 * @className PhoneFilter
 * @descriptioin:
 * @date 2025/1/13 14:49
 * @since jdk11
 */
public class PhoneFilter extends AbstractAuthenticationProcessingFilter {
    public PhoneFilter() {
        super(new AntPathRequestMatcher("/phonelogin", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("请求方式不对,必须是POSt,你的请求方式是:" + request.getMethod());
        }
        //JSON登录
        if (!request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            throw new AuthenticationServiceException("请求参数的格式不对,必须是JSON登录,你的方式是:" + request.getContentType());
        }
        Map<String, String> map = RequestBodyUtil.read(request);
        String phone = map.get("phone");
        String code = map.get("code");

        phone = phone == null ? "" : phone.trim();
        //美化代码  Ctrl+Alt+L
        code = code == null ? "" : code.trim();

        PhoneToken phoneToken = new PhoneToken(phone,code);
        //设置 ip等详细信息
        phoneToken.setDetails(this.authenticationDetailsSource.buildDetails(request));
        //调用 ProviderManager
        Authentication authentication = this.getAuthenticationManager().authenticate(phoneToken);

        return authentication;
    }
}
